//
//  WBNetworkManager.swift
//  WB
//
//  Created by macssss on 16/7/2.
//  Copyright © 2016年 macssss. All rights reserved.
//

import UIKit
import AFNetworking

//定义枚举
enum WBHTTPMethod {
    
    case GET
    case POST
}

//MARK: - 获取token和uid 方法
class WBNetworkManager: AFHTTPSessionManager {

    static let  shared: WBNetworkManager = {
        
        
        let instance = WBNetworkManager()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance

    
    }()
    
    
    //访问令牌
    
    lazy var userAccount = WBUserAceeessModel()
    
    
    //用户登录计算属性
    var userLogon: Bool {
        
        return userAccount.access_token != nil
    }
    
    //token 的过期处理
    //token 403 处理
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, compeltion:(json: AnyObject?, isSuccess: Bool)->() ) -> () {
        
        guard let token = userAccount.access_token  else {
            
            //通知用户登录
            print("没有tokeng,需要登录")
            
            //发送通知
            NotificationCenter.default.post(name: Notification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            compeltion(json: nil, isSuccess: false)
            return
        }
        
        var parameters = parameters
        if parameters == nil {
            
            parameters = [String: AnyObject]()
        }
    
        //此时paramsters 肯定有值
        parameters!["access_token"] = token
        
        //调用requse发起请求
        request(URLString: URLString, parameters: parameters, completion: compeltion)
    
        
    }
    
    
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter completion: 完成回调[json(字典／数组), 是否成功]
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String : AnyObject]?, completion: (json: AnyObject?, isSuccess: Bool) ->() ) -> () {
        
        let success = {(task: URLSessionDataTask, json: AnyObject?) -> () in
            
            completion(json: json, isSuccess: true)
            
        }
        
        
        //失败回调
        let failure = {(task: URLSessionDataTask?, error: NSError) -> () in
            
            if (task?.response as? HTTPURLResponse)?.statusCode  == 403 {
                
                print("Token 过期了")
            }
//            print(NSError())
            print("网络请求失败 ")
            
            completion(json: nil, isSuccess: false)
            
        }
        if method == .GET {
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    
   }

}
